package com.tron.dobest.security;

import com.alibaba.fastjson.JSON;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Collection;
import java.util.HashMap;

/**
 * @description 登录认证信息测试类
 * @auther gaoli
 * @create 2020-01-21
 */
@Controller
public class TronLoginController {

    @GetMapping("/login")
    public Object login() {
        return "login";
    }

    /**
     * 登录成功后返回用户信息，由from表单post跳转调用的路径，必须使用@PostMapping
     * @return
     */
    @PostMapping("/getLoginUserInfo")
    @ResponseBody
    public Object getLoginUserInfo() {
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        //用户的详细详细：账号是否过期、锁定；证书是否过期；用户名称；角色信息
        Object principal = authentication.getPrincipal();
        //授权信息
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        //访问地址；sessionId
        Object details = authentication.getDetails();
        return JSON.toJSONString(principal) + JSON.toJSONString(details) + JSON.toJSONString(authorities);
    }


    /**
     * 普通获取用户信息方法
     * @return
     */
    @GetMapping("/getUserInfo")
    @ResponseBody
    public Object getUserInfo() {
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        //用户的详细详细：账号是否过期、锁定；证书是否过期；用户名称；角色信息
        Object principal = authentication.getPrincipal();
        //授权信息
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        //访问地址；sessionId
        Object details = authentication.getDetails();
        return JSON.toJSONString(principal) + JSON.toJSONString(details) + JSON.toJSONString(authorities);
    }

    /**
     * 注销成功处理逻辑
     * @return
     */
    @GetMapping("/userLogout")
    @ResponseBody
    public Object userLogout() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("message", "注销成功");
        return map;
    }
}
